/*
 * COPYRIGHT:	2010 Christopher Smith, licenced under the GNU GPL v2; see COPYING in the top level directory
 * PROJECT:		sdedit
 * FILE:		popupbase.cpp
 * PURPOSE:		base class for subclassed popup windows
 *				
 */

unsigned const POP_RETURNTEXT = WM_APP + 100;

class PopupBase : public SubClassedWindowBase
{
public:
	DialogCallback Callback;

protected:
	BOOLEAN IsDestroying;

	PopupBase(DIALOG_CALLBACK_PROC CallbackProc, PVOID CallbackContext) :
		Callback(CallbackProc, CallbackContext),
		IsDestroying(FALSE)
	{}

	void DestroySafe()
	{
		if(!IsDestroying)
		{
			IsDestroying = TRUE;
			DestroyWindow(Wnd);
		}
	}

	void SendTextNotify(DIALOG_NOTIFY_OPERATION Operation)
	{
		int textlen = GetWindowTextLength(Wnd) + 1; 
		auto_szpod<WCHAR> text = auto_szpod_empty_ct(textlen);

		GetWindowText(Wnd, text, textlen);
		Callback.SendCallback(Operation, text);
	}

	virtual LRESULT RecieveMessage(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) override
	{
		switch(msg)
		{
		case WM_KILLFOCUS:
			SendTextNotify(DN_CLOSE_CANCEL);
			DestroySafe();
			break;

		case WM_DESTROY:
			IsDestroying = TRUE;
			break;

		case WM_KEYDOWN:
			switch(wparam)
			{
			case VK_RETURN:
				SendTextNotify(DN_CLOSE_OK);
				SetFocus(GetParent(Wnd)); //which will send a WM_KILLFOCUS here and destroy this window
				return 0;

			case VK_ESCAPE:
				SendTextNotify(DN_CLOSE_CANCEL);
				SetFocus(GetParent(Wnd));
				return 0;
			}
			break;
		};

		return __super::RecieveMessage(wnd, msg, wparam, lparam);
	}

	virtual void Create(DWORD ExtraExStyle, LPCTSTR ClassName, LPCTSTR WindowName, DWORD ExtraStyle, int x, int y, int Width, int Height, HWND Parent, HINSTANCE Instance, LPVOID Param)
	{
		__super::Create(ExtraExStyle, ClassName, WindowName, ExtraStyle | WS_BORDER | WS_POPUP, x, y, Width, Height, Parent, NULL, Instance, Param);
	}
};